package com.hc.springsecurity;

import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 当访问发生403错误时，SpringSecurity自动调用
 */
@Component
public class MyAccessDeniedHandler implements AccessDeniedHandler {
    /**
     * 处理403错误
     * @param request
     * @param response
     * @param accessDeniedException
     * @throws IOException
     * @throws ServletException
     */
    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
        //设置响应状态
        response.setStatus(HttpServletResponse.SC_FORBIDDEN);
        //设置响应类型
        response.setContentType("text/html; charset=UTF-8");
        //响应输出
        response.getWriter().println("<html><body><div style='width:800px;text-align:center;margin:auto'>权限不足，请联系管理员</div></body></html>");
        response.getWriter().flush();
    }
}
